package com.kyzh.core.pager.home.homesearch

import android.graphics.Color
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.beans.Game
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.impls.SearchImpl
import com.gushenge.core.listeners.ResultListener
import com.kyzh.core.R
import com.kyzh.core.adapters.v3.GameListBorderAdapter
import com.kyzh.core.uis.recyclerView
import com.kyzh.core.uis.titlebar
import com.kyzh.core.utils.startGameDetailActivity
import org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.swipeRefreshLayout

/**
 * Created by Administrator on 2017/5/11.
 */

class SearchArrActivity : BaseActivity() {


    private var context: SearchArrActivity? = null
    private var adapter: GameListBorderAdapter? = null
    private val list = arrayListOf<Game>()
    lateinit var root:SwipeRefreshLayout
    lateinit var recyclerView:RecyclerView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        context = this
        adapter = GameListBorderAdapter(R.layout.item_game_border, list)
        val text = intent.getStringExtra("text")?:""
        initView(text)
        root.isRefreshing = true
        initData(text)
        root.setOnRefreshListener { initData(text) }

    }

    private fun initView(tex: String) {
        verticalLayout {
            backgroundColor = Color.WHITE
            MMKVConsts.statusBarColor = Color.WHITE
            titlebar(tex).init(this,this@SearchArrActivity)
            root = swipeRefreshLayout {
                recyclerView = recyclerView {
                    leftPadding  = dip(10)
                    rightPadding  = dip(10)
                    layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
                    adapter = this@SearchArrActivity.adapter
                }
            }
        }
    }


    internal fun initData(tex: String) {
        root.isRefreshing = true
        SearchImpl().search(tex, object : ResultListener {
            override fun success(bean: Any) {
                bean as ArrayList<Game>
                if (bean.size==1){
                    startGameDetailActivity(bean[0].gid)
                    finish()
                }else{
                    list.clear()
                    list.addAll(bean)
                    adapter?.notifyDataSetChanged()
                    root.isRefreshing = false
                }
            }

            override fun error(error: String) {
                toast(error)
                adapter?.setEmptyView(R.layout.empty)
                root.isRefreshing = false
            }
        })
    }

}
